package com.dcits.tool.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcits.tool.StringUtils;

public class ExportApiData {
	public final static int XLSX = 2007; 
	
	
	public static final Map<String, String> apiTypeMark = new HashMap<String, String>();
	
	static {
		apiTypeMark.put("applicationResources", "应用资源数据");
		apiTypeMark.put("databaseResources", "数据库资源数据");
		apiTypeMark.put("clusterResources", "集群资源数据");
	}
	
	/**
	 * 生成excel文档
	 * @param data 接收到的json数据中的  data 节点
	 * @param mark 接收到的json数据中的  mark 节点
	 * @param path 生成的文件路径，不带文件名
	 * @throws Exception
	 */
	public static void export(String data, String mark, String path) throws Exception {
		JSONObject apiDataObject = JSONObject.parseObject(data);
		JSONObject apiMarkObject = JSONObject.parseObject(mark);
		
		//创建excel
		OutputStream outputStream = null; 
		path = path + File.separator + UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx";
		
		try {
			//创建excel
			Workbook wb = createWorkBook(ExcelUtil.XLSX);
			CellStyle headerStyle = createHeadCellStyle(wb);

			for (String typeKey:apiDataObject.keySet()) {
				createApiDataSheet(ExcelUtil.createSheet(wb, StringUtils.isEmpty(apiTypeMark.get(typeKey)) ? typeKey : apiTypeMark.get(typeKey))
							, apiDataObject.getJSONArray(typeKey)
							, apiMarkObject.getJSONObject(typeKey), headerStyle);				
			}
			
			outputStream = new FileOutputStream(path);
			
			wb.write(outputStream);
		} catch (Exception e) {
			// TODO: handle exception
			throw e;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
	
	
	private static void createApiDataSheet(Sheet sheet, JSONArray typeServerList, JSONObject typeMark, CellStyle headerStyle) {
		int rownum = 0;
		for (Object o:typeServerList) {
			Row titleRow = null;
			if (rownum == 0) {
				titleRow = sheet.createRow(rownum++);
			}
			Row infoRow = sheet.createRow(rownum++);
			JSONObject serverInfo = (JSONObject) o;
			int cellNum = 0;
			for (String key:typeMark.keySet()) {				
				JSONObject mark = typeMark.getJSONObject(key);
				if (titleRow != null) {
					//创建表头
					Cell titleCell = titleRow.createCell(cellNum);
					titleCell.setCellStyle(headerStyle);
					titleCell.setCellValue(mark.getString("mark"));
				}
				infoRow.createCell(cellNum).setCellValue("".equals(serverInfo.getString(key)) ? "" : serverInfo.getString(key));	
				cellNum++;
			}
			titleRow = null;
		}
	}
	
	public static Workbook createWorkBook(int type) throws IOException {
		return new XSSFWorkbook();
	}
	
	public static CellStyle createHeadCellStyle(Workbook wb) {
		CellStyle cellStyle = wb.createCellStyle();
		addAlignStyle(cellStyle, CellStyle.ALIGN_CENTER,
				CellStyle.VERTICAL_CENTER);
		addBorderStyle(cellStyle, CellStyle.BORDER_THIN,
				IndexedColors.BLACK.getIndex());
		addColor(cellStyle, IndexedColors.GREY_25_PERCENT.getIndex(),
				CellStyle.SOLID_FOREGROUND);
		return cellStyle;
	}
	
	/**
	 * cell文本位置样式
	 * 
	 * @param cellStyle
	 * @param halign
	 * @param valign
	 * @return
	 */
	public static CellStyle addAlignStyle(CellStyle cellStyle, short halign,
			short valign) {
		cellStyle.setAlignment(halign);
		cellStyle.setVerticalAlignment(valign);
		return cellStyle;
	}

	/**
	 * cell边框样式
	 * 
	 * @param cellStyle
	 * @return
	 */
	public static CellStyle addBorderStyle(CellStyle cellStyle,
			short borderSize, short colorIndex) {
		cellStyle.setBorderBottom(borderSize);
		cellStyle.setBottomBorderColor(colorIndex);
		cellStyle.setBorderLeft(borderSize);
		cellStyle.setLeftBorderColor(colorIndex);
		cellStyle.setBorderRight(borderSize);
		cellStyle.setRightBorderColor(colorIndex);
		cellStyle.setBorderTop(borderSize);
		cellStyle.setTopBorderColor(colorIndex);
		return cellStyle;
	}

	/**
	 * 给cell设置颜色
	 * 
	 * @param cellStyle
	 * @param backgroundColor
	 * @param fillPattern
	 * @return
	 */
	public static CellStyle addColor(CellStyle cellStyle,
			short backgroundColor, short fillPattern) {
		cellStyle.setFillForegroundColor(backgroundColor);
		cellStyle.setFillPattern(fillPattern);
		return cellStyle;
	}
}
